package com.cai.entity.PO;

import com.alibaba.fastjson.annotation.JSONField;
import com.cai.ex.ServiceException;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Title: UserDetailsImpl
 * @Author RuoLi
 * @Package com.cai.entity.PO
 * @Date 2024/1/12 10:47
 * @description: UserDetails实现类
 */
@Data
public class UserDetailsImpl implements UserDetails, Serializable {
    private MyPrincipal myPrincipal;
    private String password;
    private List<String> permissions;
    private String role;

    @JSONField(serialize = false)
    List<SimpleGrantedAuthority> authorities;

    // 获取用户权限
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if (permissions.isEmpty()) throw new ServiceException("List<String> permissions 数据为空");
        if (authorities != null) return authorities;

        authorities = permissions.stream().map(SimpleGrantedAuthority::new)
                .collect(Collectors.toList());
        return authorities;
    }

    // 获取用户密码
    @Override
    public String getPassword() {
        return password;
    }

    // 获取用户账号
    @Override
    public String getUsername() {
        return myPrincipal.getUsername();
    }

    // 获取用户是否过期
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    // 获取用户是否锁定
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    // 获取用户凭证（密码）是否没过期
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    // 获取用户是否可用
    @Override
    public boolean isEnabled() {
        return true;
    }
}
